<?php


namespace App\Http\Controllers;

use App\Models\FishingSite;
use App\Models\FishingSiteMonitor;
use App\Models\LiveRoom;
use App\Models\User;
use App\Server\AliOSS;
use App\Server\Constants;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

/**
 * 钓点
 * Class FishingSiteController
 * @package App\Http\Controllers
 */
class FishingSiteController extends Controller
{
    public function site(Request $request)
    {
        $lat = $request->lat;
        $lng = $request->lng;
        if (!$lat) {
            $location = default_location();
            $lat = $location['lat'];
            $lng = $location['lng'];
        }

        $model = DB::table('fishing_sites')->where('home_status', 1)->select(['id', 'name', 'img', 'address', 'type', 'tags', 'monitor']);
        if ($request->bookmark == 1) {
            $ids = DB::table('site_bookmarks')->where('uid', $request->uid)->pluck('site_id');
            $model = $model->whereIn('id', $ids);
        }
        $model->addSelect(\DB::raw("acos(cos(" . $lat . "*pi()/180)*cos(map_lat*pi()/180)*cos(" . $lng . "*pi()/180-map_lng*pi()/180)+sin(" . $lat . "*pi()/180)*sin(map_lat * pi()/180)) * 6367000 AS distance"))->orderBy('distance','ASC');
        $data = $model->paginate(10);
        foreach ($data as &$item) {
            $item->img = img_url(AliOSS::getThumbName($item->img));
            $item->distance = distance_text($item->distance, $request->lat);
            $tags = [Constants::$siteType[$item->type]];
            if ($item->tags) {
                $tags = array_merge($tags, explode(',', $item->tags));
                $tags = array_slice($tags, 0, 3); //列表只显示3个标签
            }
            $item->tags = $tags;
            $item->live = LiveRoom::where(['site_id' => $item->id, 'status' => 1])->first() ? 1 : 0;
        }
        return $this->success($data);
    }


    /**
     * 钓场详情
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Throwable
     */
    public function details(Request $request)
    {
        throw_err(!$request->id, 'id不能为空');
        $lat = $request->lat;
        $lng = $request->lng;
        if (!$lat) {
            $location = default_location();
            $lat = $location['lat'];
            $lng = $location['lng'];
        }

        $model = DB::table('fishing_sites')->where('id', $request->id)
            ->select(['id', 'name', 'address', 'map_lat', 'map_lng', 'carousel', 'boos', 'boos_phone', 'introduce', 'tags', 'type', 'monitor']);
        $model->addSelect(\DB::raw("acos(cos(" . $lat . "*pi()/180)*cos(map_lat*pi()/180)*cos(" . $lng . "*pi()/180-map_lng*pi()/180)+sin(" . $lat . "*pi()/180)*sin(map_lat * pi()/180)) * 6367000 AS distance"))->orderBy('distance','ASC');
        $data = $model->first();
        if ($data->carousel) {
            $carousel = json_decode($data->carousel, true);
            foreach ($carousel as &$item) {
                $item = [
                    'thumb' => img_url(AliOSS::getBannerName($item)),
                    'original' => img_url($item),
                ];
            }
            $data->carousel = $carousel;
        }
        $tags = [Constants::$siteType[$data->type]];
        if ($data->tags) {
            $tags = array_merge($tags, explode(',', $data->tags));
        }
        $data->tags = $tags;
        $data->distance = distance_text($data->distance, $request->lat);
        $liveing = LiveRoom::where(['site_id' => $data->id, 'status' => 1])->orderByDesc('id')->first();
        $liveRooms = LiveRoom::where(['site_id' => $data->id, 'status' => 1])->count();
        $data->is_bookmark = DB::table('site_bookmarks')->where(['uid' => $request->uid, 'site_id' => $request->id])->exists() ? 1 : 0;
        $data->live = [
            'room_count' => $liveRooms,
            'avatar'     => $liveing ? img_url(User::where('id', $liveing->uid)->value('avatar')) : ''
        ];
        return $this->success($data);
    }

    /**
     * 热门钓场
     * @return \Illuminate\Http\JsonResponse
     */
    public function hot()
    {
        $data = FishingSite::where('is_host', 1)->select(['id', 'name'])->get();
        return $this->success($data);
    }

    /**
     * 搜索补全提示， select2
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Throwable
     */
    public function searchHint(Request $request)
    {
        $lat = $request->lat;
        $lng = $request->lng;
        if (!$lat) {
            $location = default_location();
            $lat = $location['lat'];
            $lng = $location['lng'];
        }
        if (!$request->keyword) {
            return $this->success([]);
        }
        $data = DB::table('fishing_sites')
            ->where('name', 'like', "%{$request->keyword}%")
            ->select(['id', 'name', 'img'])
            ->addSelect(\DB::raw("acos(cos(" . $lat . "*pi()/180)*cos(map_lat*pi()/180)*cos(" . $lng . "*pi()/180-map_lng*pi()/180)+sin(" . $lat . "*pi()/180)*sin(map_lat * pi()/180)) * 6367000 AS distance"))->orderBy('distance','ASC')
            ->paginate(10);
        foreach ($data as &$item) {
            $item->distance = distance_text($item->distance, $request->lat);
            $item->img = img_url($item->img);
        }
        return $this->success($data);
    }

    /**
     * 钓点地图
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Throwable
     */
    public function siteMap(Request $request)
    {
        $lat = $request->lat;
        $lng = $request->lng;
        if (!$lat) {
            $location = default_location();
            $lat = $location['lat'];
            $lng = $location['lng'];
        }

        $model = DB::table('fishing_sites')->where('map_status', 1)->select(['id', 'name', 'img', 'type', 'tags', 'map_lat', 'map_lng']);
        $model->addSelect(\DB::raw("acos(cos(" . $lat . "*pi()/180)*cos(map_lat*pi()/180)*cos(" . $lng . "*pi()/180-map_lng*pi()/180)+sin(" . $lat . "*pi()/180)*sin(map_lat * pi()/180)) * 6367000 AS distance"))->orderBy('distance','ASC');

        //收藏
        if ($request->bookmark) {
            $ids = DB::table('site_bookmarks')->where('uid', $request->uid)->pluck('site_id');
            $data = $model->whereIn('id', $ids)->get();
        } else {
            $data = $model->get();
        }
        foreach ($data as &$item) {
            $item->img = img_url(AliOSS::getThumbName($item->img));
            $item->distance = distance_text($item->distance, $request->lat);
            $tags = [Constants::$siteType[$item->type]];
            if ($item->tags) {
                $tags = array_merge($tags, explode(',', $item->tags));
            }
            $item->tags = $tags;
        }
        return $this->success($data);
    }

    /**
     * 收藏与取消收藏
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Throwable
     */
    public function bookmark(Request $request)
    {
        throw_err(!$request->id, '钓场id不能为空');
        throw_err(!$request->type, 'type不能为空');
        $bookmark = DB::table('site_bookmarks')->where(['uid' => $request->uid, 'site_id' => $request->id])->first();
        if ($request->type == 1 && !$bookmark) {
            DB::table('site_bookmarks')->insert([
                'uid' => $request->uid,
                'site_id' => $request->id,
                'created_at' => date('Y-m-d H:i:s')
            ]);
        }
        if ($request->type == 2 && $bookmark) {
            DB::table('site_bookmarks')->delete($bookmark->id);
        }
        return $this->success();
    }

    /**
     * 鱼情监控
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Throwable
     */
    public function monitorPhoto(Request $request)
    {
        throw_err(!$request->site_id, '钓场id不能为空');
        $data = FishingSiteMonitor::where('site_id', $request->site_id)->select('id', 'img', 'time')->orderByDesc('id')->paginate(10)->toArray();
        $imgs = [];
        foreach ($data['data'] as $k) {
            $date = date('Y-m-d', strtotime($k['time']));
            if (!array_key_exists($date, $imgs)) {
                $imgs[$date] = ['date' => $date];
            }
            $k['time'] = date('H:i', strtotime($k['time']));
            $imgs[$date]['list'][] = $k;
        }
        $data['data'] = array_values($imgs);
        return $this->success($data);
    }

    /**
     * 最新拍摄照片
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Throwable
     */
    public function newMonitorPhoto(Request $request)
    {
        throw_err(!$request->site_id, '钓场id不能为空');
        $data = FishingSiteMonitor::where('site_id', $request->site_id)->select('img', 'time')->orderByDesc('id')->limit(1)->first();
        return $this->success($data);
    }

}